import serial
import threading
import serial.tools.list_ports


class Ser:
    def __init__(self):
        self.NOEND = True  # 是否读取结束

    def showPort(self):
        port_list = list(serial.tools.list_ports.comports())

        ports = []
        if len(port_list) <= 0:
            print('提示', '无端口可用')
        else:
            for i in port_list:
                ports.append(i[0])
        return ports

    def openPort(self, port, baudrate=9600, bytesize=8, parity='N', stopbits='1'):
        try:
            self.ser = serial.Serial(port, baudrate, bytesize=serial.EIGHTBITS, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, timeout=None)
        except Exception as e:
            print("error!", e)

    def stop(self):
        self.ser.close()

    def sendData(self, text):
        self.ser.write(text.encode("gbk"))
        self.NOEND = True
    def recvData(self):
        while self.NOEND:
            if self.ser.in_waiting:
                data = self.ser.read(self.ser.in_waiting).decode("gbk")
                self.NOEND = False
                return data


